<template>
  <div class="juanliandiv frcc">
    <!-- 卷帘: -->
    <el-switch
      v-model="issplit"
      :active-value="true"
      :inactive-value="false"
      inline-prompt
      active-text="卷帘"
      inactive-text="卷帘"
      @change="splitchange"
    >
    </el-switch>
    &nbsp;
    共{{imagelist.length}}个
  </div>
  <div class="rollercom" style="">
    <el-scrollbar>
      <div
        v-for="item in imagelist"
        style="padding: 5px 10px; display: flex; cursor: pointer;"
        class="imgitemdiv"
        @mouseover="handleMouseOver(item)"
        @mouseout="handleMouseOut(item)"
      >
        <div style="" class="titlenamediv">
          <div>
            名称：
            <n-ellipsis style="max-width: 90px">
              {{ item.name }}
            </n-ellipsis>
          </div>
          <div>
            <el-button type="" size="small" @click="deleteItem(item)"> 删除 </el-button>
          </div>
        </div>
        <el-radio-group v-model="item.type" @change="layerclick(item)">
          <el-radio :label="0">显示</el-radio>
          <el-radio :label="-1">隐藏</el-radio>
          <el-radio :label="1" v-if="issplit">左</el-radio>
          <el-radio :label="2" v-if="issplit">右</el-radio>
        </el-radio-group>
      </div>

    </el-scrollbar>
  </div>
</template>
<script setup>
import {
  onMounted,
  ref,
  onUnmounted,
  defineProps,
  defineExpose,
  getCurrentInstance,
} from "vue";

import { v1 } from "uuid";

import _ from "lodash";

// import { apiList } from "@/api/apiList";

import { useEarthStore } from "@/stores/earth";

import TIFFImageryProvider from "tiff-imagery-provider";

import { apiList } from "@/api/apiList";

// import { isOK } from "@/utils/resUtils";

// import { getFinalPos } from "@/hooks//earth/utils";

let props = defineProps(["itemoptions"]);

const earthStore = useEarthStore();

const imagelist = ref([]);
let _imagelayer = {};

window.rollercom = getCurrentInstance();

let _srs = "EPSG:4326";

let issplit = ref(false);

function deleteItem(item) {
  // 只能通过数组删除元素来删除

  let resid = "";
  earth.sceneTree.$refs.rollergroup.children.map((item1, index) => {
    if (item1.czmObject.xbsjGuid == item.index) {
      resid = index;
    }
  });
  earth.sceneTree.$refs.rollergroup.children.splice(resid, 1);

  // 这种方法不行
  // console.log(item);
  // earth.getObject(item.index).destroy()

  setTimeout(() => {
    updatelayer();
  }, 0);
}

// 高亮悬浮
let allitem = [];
let alliteme = [];
let _layertmp = new Cesium.CustomDataSource('tmplayer')
viewer.dataSources.add(_layertmp);

let hoveritem = "";
// hover事件
function handleMouseOver(params) {
  if (hoveritem != params.id) {
    // 取消高亮并重新设置

    if (hoveritem != "") {
      alliteme.map(item => {
        if (item.id == hoveritem) {
          console.log();
          item.polygon.outlineColor = Cesium.Color.fromCssColorString("#00ffff");
          item.polygon.material = Cesium.Color.fromCssColorString("#00ff0000");
        }
      });
    }

    hoveritem = params.id;
    alliteme.map(item => {
      if (item.id == params.id) {
        item.polygon.outlineColor = Cesium.Color.fromCssColorString("#00ff0022");
        item.polygon.material = Cesium.Color.fromCssColorString("#00ff0022");
      }
    });
  }
}
function handleMouseOut(params) {
  hoveritem = "";
  alliteme.map(item => {
    if (item.id == params.id) {
      item.polygon.outlineColor = Cesium.Color.fromCssColorString("#00ffff00");
      item.polygon.material = Cesium.Color.fromCssColorString("#00ff0000");
    }
  });
}


function loadtmprectangle() {
  _layertmp.entities.removeAll()
  alliteme = [];
  allitem.map(iitem => {
    Cesium.GeoJsonDataSource.load(iitem.item, {
      stroke: Cesium.Color.fromCssColorString("#00ffff00"),
      fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.0),
      strokeWidth: 3,
    }).then(res => {
      res.entities.values.map(item => {
        _layertmp.entities.add(item);
        alliteme.push(item)
      });
      // alliteme.push()
    });
  })
}


function splitchange(params) {
  if (issplit.value) {
    earth.camera.viewport.splitX = 0.5;
  } else {
    // 关闭
    // 恢复默认状态
    imagelist.value.map(item => {
      item.type = 0;
      layerclick(item);
    });
    earth.camera.viewport.splitX = 1.0;
  }
}

function addimage(item) {
  console.log(item);

  let rec = getrectangle(item);

  let params = {
    layername: "taiwan13-1",
    tifpath: "taiwan13-1.tif",
  };
  allitem.push(item)

  params.tifpath = item.imgpath;
  let namearr = item.imgpath.split("/");
  params.layername = namearr.pop().split(".")[0];

  apiList.shujuguanli.genWmsService(params).then(res => {
    // wmts
    let basemapSource = new Cesium.WebMapTileServiceImageryProvider({
      //  对与url  很多博客都说要进行 如下拼接
      // 后端返回的wmts/rest/{layer}/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/png
      // 其实不用拼接  只需要后端返回的/wtms路径即可
      url: "/geoserver/gwc/service/wmts", //服务地址 服务地址只需要后端返回的 /WMTS   不需要给后面拼接任何东西，
      layer: `test_tif:${params.layername}`, //图层名称 : "pucheng:satellite"
      style: "",
      format: "image/png",
      tileMatrixSetID: _srs, // "EPSG:900913"
      // 地图飞入  定位的坐标  后端返回的数据
      rectangle: rec,
      // 必须加  不然地图出不来
      //之所以要在这里提出这个tileMatrixLabels参数，是因为GeoServer在缓冲切分瓦片时对每一个缩放级别的存储目录没有使用相应的数字，而使用了网格+级别的方式来命名，如“EPSG:9100913:10”表示的是使用“EPSG:9100913”网格切分的第10级瓦片。
      tileMatrixLabels: [
        `${_srs}:0`,
        `${_srs}:1`,
        `${_srs}:2`,
        `${_srs}:3`,
        `${_srs}:4`,
        `${_srs}:5`,
        `${_srs}:6`,
        `${_srs}:7`,
        `${_srs}:8`,
        `${_srs}:9`,
        `${_srs}:10`,
        `${_srs}:11`,
        `${_srs}:12`,
        `${_srs}:13`,
        `${_srs}:14`,
        `${_srs}:15`,
        `${_srs}:16`,
        `${_srs}:17`,
        `${_srs}:18`,
        `${_srs}:19`,
        `${_srs}:20`,
      ],
      // 必须加  不然地图出不来
      tilingScheme: new Cesium.GeographicTilingScheme({
        //此处很重要，很重要。。。
        numberOfLevelZeroTilesX: 2,
        numberOfLevelZeroTilesY: 1,
      }),
      // tilematrixset: _srs,
      // maximumLevel: 18,
    });

    let name = params.layername;
    let wmsobj = earth.sceneTree.$refs.rollergroup.children.push({
      ref: name,
      czmObject: {
        xbsjType: "Imagery",
        name: params.layername + "|" + item.item.id,
        xbsjImageryProvider: {
          type: "WebMapServiceImageryProvider",
        },
      },
    });

    setTimeout(() => {
      const layerRef = earth.sceneTree.$refs[name];
      layerRef.czmObject.xbsjImageryProvider.WebMapServiceImageryProvider._imageryProvider = basemapSource;
      // 将对 _imagelayer 的设置放在 then() 方法内部
      _imagelayer[layerRef.czmObject.xbsjGuid] = layerRef.czmObject;
      window._imagelayer = _imagelayer;
    }, 500);
    updatelayer();
  });

  return;

  let name = item.filename;
  let wmsobj = earth.sceneTree.$refs.rollergroup.children.push({
    ref: name,
    czmObject: {
      xbsjType: "Imagery",
      name: item.domname,
      xbsjImageryProvider: {
        type: "WebMapServiceImageryProvider",
      },
    },
  });

  const layerRef = earth.sceneTree.$refs[name];
  layerRef.czmObject.xbsjImageryProvider.WebMapServiceImageryProvider._imageryProvider = provider;
  // 将对 _imagelayer 的设置放在 then() 方法内部
  _imagelayer[layerRef.czmObject.xbsjGuid] = layerRef.czmObject;
}

function updatelayer(params) {
  setTimeout(() => {
    // 获取所有影像
    imagelist.value = [];
    _imagelayer = {};
    modellist.value = [];
    _modellayer = {};
    earth.sceneTree.$refs.rollergroup.children.map(item => {
      // console.log(item, "item");
      // item.czmObject.enabled = false;
      if (item.czmObject.xbsjType == "Imagery") {
        imagelist.value.push({
          name: item.czmObject.name.split("|")[0],
          id: item.czmObject.name.split("|")[1],
          type: 0,
          index: item.czmObject.xbsjGuid,
        });
        _imagelayer[item.czmObject.xbsjGuid] = item.czmObject;
      }
      // 获取所有模型
      if (item.czmObject.xbsjType == "Tileset") {
        modellist.value.push({
          name: item.czmObject.name,
          type: 0,
          index: item.czmObject.xbsjGuid,
        });
        _modellayer[item.czmObject.xbsjGuid] = item.czmObject;
      }
    });
    // layerclick(imagelist.value[0]);

    // _modellayer[Object.keys(_modellayer)[0]].flyTo();
    loadtmprectangle()
  }, 200);
}

function getrectangle(item) {
  // 计算外包围盒
  let west = Number.POSITIVE_INFINITY;
  let south = Number.POSITIVE_INFINITY;
  let east = Number.NEGATIVE_INFINITY;
  let north = Number.NEGATIVE_INFINITY;

  item.item.geometry.coordinates[0].map(iitem => {
    west = Math.min(west, Cesium.Math.toRadians(iitem[0]));
    south = Math.min(south, Cesium.Math.toRadians(iitem[1]));
    east = Math.max(east, Cesium.Math.toRadians(iitem[0]));
    north = Math.max(north, Cesium.Math.toRadians(iitem[1]));
  });

  const rectangle = new Cesium.Rectangle(west, south, east, north);

  return rectangle;
}

const layerclick = item => {
  console.log(_imagelayer, "_imagelayer");
  switch (item.type) {
    case 0:
      _imagelayer[item.index].enabled = true;
      _imagelayer[item.index].splitDirection = "ImagerySplitDirection.NONE";
      break;
    case -1:
      _imagelayer[item.index].enabled = false;
      _imagelayer[item.index].splitDirection = "ImagerySplitDirection.NONE";
      break;
    case 1:
      _imagelayer[item.index].enabled = true;
      _imagelayer[item.index].splitDirection = "ImagerySplitDirection.LEFT";

      break;
    case 2:
      _imagelayer[item.index].enabled = true;
      _imagelayer[item.index].splitDirection = "ImagerySplitDirection.RIGHT";

      break;

    default:
      break;
  }
};

const modellist = ref([]);
let _modellayer = {};

const modelclick = item => {
  switch (item.type) {
    case 0:
      _modellayer[item.index].enabled = false;
      _modellayer[item.index].xbsjLeftTopView = true;
      _modellayer[item.index].xbsjLeftBottomView = true;
      _modellayer[item.index].xbsjRightTopView = true;
      _modellayer[item.index].xbsjRightBottomView = true;
      break;
    case 1:
      _modellayer[item.index].enabled = true;
      _modellayer[item.index].xbsjLeftTopView = true;
      _modellayer[item.index].xbsjLeftBottomView = true;
      _modellayer[item.index].xbsjRightTopView = false;
      _modellayer[item.index].xbsjRightBottomView = false;

      break;
    case 2:
      _modellayer[item.index].enabled = true;
      _modellayer[item.index].xbsjLeftTopView = false;
      _modellayer[item.index].xbsjLeftBottomView = false;
      _modellayer[item.index].xbsjRightTopView = true;
      _modellayer[item.index].xbsjRightBottomView = true;

      break;

    default:
      break;
  }
};

onUnmounted(() => {
  earth.sceneTree.$refs.rollergroup.children = [];
  earth.camera.viewport.splitX = 1.0;
});

onMounted(() => {
  // earth.camera.viewport.splitX = 0.5;
  //向图层树添加影像和模型
  let haslayer = false;
  earth.sceneTree.root.children.map(item => {
    if (_.has(item, "title") && item["title"] == "卷帘分组") {
      haslayer = true;
    }
  });
  if (!haslayer) {
    earth.sceneTree.root.children.push({
      title: "卷帘分组",
      ref: "rollergroup",
      children: [],
    });
  }

  return;

  // 添加模型
  let item = earthStore.pannellist["rollerpannel"].options.data;

  // 数据源

  // Promise.all([
  //   apiList.queryDataByType({ target_id: item.id, type: "obj" }),
  //   apiList.queryDataByType({ target_id: item.id, type: "tif" }),
  // ]).then((res) => {
  // 模型数据
  // if (isOK(res[0])) {
  //   res[0].result.map((item: any) => {
  //     if (item.relpath && item.relpath.includes("json")) {
  //       earth.sceneTree.$refs.rollergroup.children.push({
  //         czmObject: {
  //           xbsjType: "Tileset",
  //           xbsjGuid: v1(),
  //           name: item.keywords == "" ? item.filename : item.keywords,
  //           url: `api/download/${item.relpath.replaceAll("\\", "/")}`,
  //           xbsjClippingPlanes: {},
  //           xbsjUseOriginTransform: false,
  //           xbsjCustomShader: {},
  //         },
  //       });
  //     }
  //   });
  // }

  // 影像数据
  // if (isOK(res[1])) {
  // let res = [{ result: [{ filename: "b.tif", keywords: "关岛影像" },{ filename: "c.tif", keywords: "关岛影像" }] }];
  let res = [{ result: [] }];
  props.itemoptions.data.map(item => {
    res[0].result.push({
      keywords: item.filename,
      ...item,
    });
  });
  res[0].result.map((item, index) => {
    // console.log(getFinalPos(item.details.geometry.center_coording,item.details.properties.spatial_ref));
    let name = item.filename;
    let wmsobj = earth.sceneTree.$refs.rollergroup.children.push({
      ref: name,
      czmObject: {
        xbsjType: "Imagery",
        name: item.domname,
        xbsjImageryProvider: {
          type: "WebMapServiceImageryProvider",
        },
      },
    });

    // TIFFImageryProvider.fromUrl(`${projectapiprefix}${item.filename}`).then((provider) => {
    // earth.sceneTree.$refs[
    //   name
    // ].czmObject.xbsjImageryProvider.WebMapServiceImageryProvider._imageryProvider = provider
    //
    // });
    setTimeout(() => {
      console.log(item.filename, "item.filename");
      TIFFImageryProvider.fromUrl(`${item.filename}`).then(provider => {
        console.log(provider, "provider");
        const layerRef = earth.sceneTree.$refs[name];
        layerRef.czmObject.xbsjImageryProvider.WebMapServiceImageryProvider._imageryProvider = provider;
        // 将对 _imagelayer 的设置放在 then() 方法内部
        _imagelayer[layerRef.czmObject.xbsjGuid] = layerRef.czmObject;
        viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            provider.origin[0],
            provider.origin[1],
            100000.0
          ),
          orientation: {
            heading: Cesium.Math.toRadians(0.0),
            pitch: Cesium.Math.toRadians(-90.0),
            roll: 0.0,
          },
        });
      });
    }, 500);
  });
  // }
  setTimeout(() => {
    // 获取所有影像
    imagelist.value = [];
    _imagelayer = {};
    modellist.value = [];
    _modellayer = {};
    earth.sceneTree.$refs.rollergroup.children.map(item => {
      console.log(item, "item");
      item.czmObject.enabled = false;
      if (item.czmObject.xbsjType == "Imagery") {
        imagelist.value.push({
          name: item.czmObject.name,
          type: 2,
          index: item.czmObject.xbsjGuid,
        });
        _imagelayer[item.czmObject.xbsjGuid] = item.czmObject;
      }
      // 获取所有模型
      if (item.czmObject.xbsjType == "Tileset") {
        modellist.value.push({
          name: item.czmObject.name,
          type: 0,
          index: item.czmObject.xbsjGuid,
        });
        _modellayer[item.czmObject.xbsjGuid] = item.czmObject;
      }
    });
    layerclick(imagelist.value[0]);
    // _modellayer[Object.keys(_modellayer)[0]].flyTo();
  }, 200);
  // });
  return;
});

const closewindow = () => {
  earthStore.resultlistsplitshowindex = -1;
};

defineExpose({
  closewindow,
  addimage,
});
</script>
<style lang="scss">
.titlenamediv {
  display: flex;
  justify-content: space-between;
}

.imgitemdiv {
  border: solid 1px #fff5;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  margin: 5px 0px;
  
}

.xbsjEarthSpliter {
  width: 8px !important;
}

.rollercom {
  padding: 0px 5px;
  height: 100%;
}
</style>
